package com.minelx.woods.server.service;

import com.alibaba.fastjson.JSONObject;
import com.minelx.woods.server.entity.Review;
import com.minelx.woods.server.entity.Reviews;
import com.minelx.woods.server.entity.Tasks;
import com.minelx.woods.server.entity.values.ReviewValues;
import com.minelx.woods.server.entity.values.TaskValues;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.minelx.woods.server.entity.TaskConstants.READY;
import static java.util.stream.Collectors.toList;

@Service
public class ReviewService {
	private final Reviews reviews;

	private final Tasks tasks;

	public ReviewService(Reviews reviews, Tasks tasks) {
		this.reviews = reviews;
		this.tasks = tasks;
	}

	public ResponseEntity<?> reject(String reviewId, String operator) {
		reviews.id(reviewId).reject(operator);
		return ResponseEntity.ok().build();
	}

	public ResponseEntity<?> approve(String reviewId, String operator) {
		Review review = reviews.id(reviewId);
		boolean isReviewCompleted  = review.approve(operator);
		if (isReviewCompleted) {
			// mark the corresponding task of the review as: READY
			String taskId = review.values().getTaskId();
			tasks.id(taskId).markAs(READY);
		}
		return ResponseEntity.ok().build();
	}

	public ResponseEntity<ReviewValues> postReview(String submitter, String reviewName, List<String> reviewers, JSONObject infoValues) {
		TaskValues pushedTask = tasks.push(infoValues);
		// if reviewers is empty, skip reviewing
		if (reviewers.isEmpty()) {
			tasks.id(pushedTask.getId()).markAs(READY);
		}
		Review createdReview = reviews.createReview(submitter, reviewName, pushedTask.getId(), reviewers);
		return ResponseEntity.ok(createdReview.values());
	}

	public ResponseEntity<List<ReviewValues>> list(int offset, int length) {
		return ResponseEntity.ok(reviews.range(offset, length).stream()
				.map(Review::values)
				.collect(toList()));
	}
}
